﻿using AutoWelding.BLL;
using AutoWelding.Models;
using AutoWelding.Utils;

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace AutoWelding.Views.Logs
{
    public partial class LogsForm : Form
    {
        public LogsForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 页面载入时，调用显示功能
        /// </summary>
        private void LogsForm_Load(object sender, EventArgs e)
        {
            BindLogsData();
        }

        /// <summary>
        /// 显示功能: 显示所有日志数据
        /// </summary>
        public void BindLogsData()
        {
            string logLevel = cmb_logLevel.Text;
            DateTime startTime = Convert.ToDateTime(dtp_startTime.Text);
            DateTime endTime = Convert.ToDateTime(dtp_endTime.Text);
            if (logLevel == "——请选择——")
                logLevel = "All";
            try
            {
                LogsBLL logsBLL = new LogsBLL();
                // 从BLL层获取数据
                List<LogsModel> logsList = logsBLL.GetLogsList(logLevel, startTime, endTime);

                // 绑定到DataGridView
                dgv_logsData.DataSource = logsList;

                // 可选设置
                //dgv_logsData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                //dgv_logsData.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }
            catch (Exception ex)
            {
                // UI层 记录日志 向用户提示
                LogHelper.Error(this.GetType(), "加载数据失败，请检查数据库。");
                MessageBox.Show("加载数据失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 查询按钮，重新调用显示功能
        /// </summary>
        private void btn_select_Click(object sender, EventArgs e)
        {
            BindLogsData();
        }

        /// <summary>
        /// dgv控件的 CellFormatting 事件，用于设置单元格内容的显示格式
        /// </summary>
        private void dgv_logsData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            Color colorError = Color.FromArgb(255, 107, 107);   // #FF6B6B 暗珊瑚红（Dark Coral）
            Color colorWarn = Color.FromArgb(255, 179, 71);   // #FFB347 杏黄色（Apricot）或中橙色
            Color colorInfo = Color.FromArgb(119, 221, 119);  // #77DD77 浅苔绿（Pastel Green）
            Color colorDebug = Color.FromArgb(106, 156, 255);  // #6A9CFF 柔和蓝（Soft Periwinkle）
            Color colorOther = Color.FromArgb(176, 176, 176);  // #B0B0B0 浅灰色（Light Gray）
            try
            {
                // 日志类别 列，如果是Error 背景变红
                if (dgv_logsData.Columns[e.ColumnIndex].Name == "log_level")
                {
                    string value = Convert.ToString(e.Value);
                    // log_level 的大小写问题 疑惑
                    switch (value)
                    {
                        case "ERROR":
                            e.CellStyle.BackColor = colorError;
                            break;
                        case "WARN":
                            e.CellStyle.BackColor = colorWarn;
                            break;
                        case "INFO":
                            e.CellStyle.BackColor = colorInfo;
                            break;
                        case "DEBUG":
                            e.CellStyle.BackColor = colorDebug;
                            break;
                        default:
                            e.CellStyle.BackColor = colorOther;
                            break;
                    }
                    // 可选 更改内容显示
                    //e.Value = lastValue == 1 ? "在职" : "离职";
                    e.FormattingApplied = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// dgv控件的 DataBindingComplete 事件，用于更改数据源列表
        /// </summary>
        private void dgv_logsData_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            // 在数据绑定完成后修改列标题（只执行一次）
            dgv_logsData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            foreach (DataGridViewColumn column in dgv_logsData.Columns)
            {
                switch (column.Name)
                {
                    case "id":
                        column.HeaderText = "序号"; // 日志ID 记录编号 日志序号 事件ID
                        column.Width = 60;
                        break;
                    case "log_level":
                        column.HeaderText = "类别";
                        column.Width = 60;
                        break;
                    case "log_message":
                        column.HeaderText = "消息内容";
                        break;
                    case "logger":
                        column.HeaderText = "记录日志的类名";
                        break;
                    case "log_time":
                        column.HeaderText = "日志时间";
                        column.Width = 120;
                        break;
                }
            }
        }

        /// <summary>
        /// 导出按钮
        /// </summary>
        private void btn_output_Click(object sender, EventArgs e)
        {
            if(dgv_logsData.Rows.Count > 0)
            {
               ExcelUtils.ExportToExcel(dgv_logsData);
            }
            else
            {
                MessageBox.Show("没有数据可导出！","提示");
            }
        }
    }
}
